package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

const FeishuWebhookURL = "https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxx-xxxx-xxxx"

type FeishuTextMsg struct {
	MsgType string `json:"msg_type"`
	Content struct {
		Text string `json:"text"`
	} `json:"content"`
}

// SendFeishuTextMsg 发送飞书文本消息
func SendFeishuTextMsg(content string) error {
	msg := FeishuTextMsg{
		MsgType: "text",
	}
	msg.Content.Text = content

	body, err := json.Marshal(msg)
	if err != nil {
		return fmt.Errorf("marshal error: %w", err)
	}

	req, err := http.NewRequest("POST", FeishuWebhookURL, bytes.NewBuffer(body))
	if err != nil {
		return fmt.Errorf("new request error: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("http error: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
	}

	return nil
}
